<template>
  <div>
    <div ref="toolbar"></div>
    <div ref="editor"></div>
  </div>
</template>
<script>
import E from "wangeditor";
import apiConfig from "@/utils/apiConfig";
import {Message} from 'element-ui'
const { api } = apiConfig;
export default {
  props: {
    html: {
      type: String,
      default: ""
    },
    content: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      editor: null,
      uploadUrl: api["imgUpload"]
    };
  },
  mounted() {
    let _this = this;
    this.editor = new E(this.$refs.editor);
    this.editor.customConfig.onchange = html => {
      _this.$emit("change", html, _this.editor.txt.text());
    };
    this.editor.customConfig.debug = true;
    this.editor.customConfig.pasteFilterStyle = false;
    this.editor.customConfig.pasteIgnoreImg = true;
    this.editor.customConfig.uploadImgShowBase64 = false; // base 64 存储图片
    this.editor.customConfig.uploadImgServer = this.uploadUrl; // 配置服务器端地址
    this.editor.customConfig.uploadImgHeaders = {}; // 自定义 header
    this.editor.customConfig.uploadFileName = "file"; // 后端接受上传文件的参数名
    this.editor.customConfig.uploadImgMaxSize = 2 * 1024 * 1024; // 将图片大小限制为 2M
    // this.editor.customConfig.uploadImgMaxLength = 6; // 限制一次最多上传 6 张图片
    this.editor.customConfig.uploadImgTimeout = 4000; // 设置超时时间
    this.editor.customConfig.uploadImgHooks = {
      fail: (xhr, editor, result) => {
        // 插入图片失败回调
      },
      success: (xhr, editor, result) => {
        // 图片上传成功回调
        console.log(_this.editor.txt.html(),result)
      },
      timeout: (xhr, editor) => {
        // 网络超时的回调
        Message.error('网络请求超时！');
      },
      error: (xhr, editor) => {
        // 图片上传错误的回调
        Message.error('图片上传错误！');
      },
      customInsert: (insertImg, result, editor) => {
        // 图片上传成功，插入图片的回调
        if(result.content&&result.content.url){
            insertImg(result.content.url)
        }
      }
    };
    this.editor.create();
  },
  methods: {},
  watch: {
    /**
     * 监听content内容
     */
    html(newVal, oldVal) {
      this.editor.txt.html(newVal);
    }
  }
};
</script>
<style lang='scss' scoped>
</style>